﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Algorithm.SortAlgorithm
{
    public class TaskScheduling
    {
        public static Task[] Schedul(params Task[] tasks)
        {
            List<Task> result = new List<Task>();
            var tmp = tasks.OrderBy((t) => { return int.MaxValue - t.Punishment; }).ToArray();
            for (int i = 0; i < tmp.Length; i++)
            {
                result.Add(tmp[i]);
                if (!isAlone(result.ToArray()))
                {
                    result.RemoveAt(result.Count - 1);
                }
            }

            return result.OrderBy((t) => { return t.BeforeThisIndex; }).ToArray();
        }

        /// <summary>
        /// 判断任务是否独立
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        private static bool isAlone(Task[] task)
        {
            for(int i = 1;i<=task.Length;i++)
            {
                if (!(task.Count((t) => { return t.BeforeThisIndex <= i; }) <= i))
                {
                    return false;
                }
            }
            return true;
        }
    }

    public class Task
    {
        public int BeforeThisIndex;
        public double Punishment;
    }
}
